package com.hq.service.impl;

import org.apache.ibatis.session.SqlSession;

import com.hq.dao.AccountMapper;
import com.hq.dao.UserInfoMapper;
import com.hq.pojo.Account;
import com.hq.pojo.UserInfo;
import com.hq.service.AccountService;
import com.hq.utils.Common;
import com.hq.utils.MyBatisUtil;

public class AccountImpl implements AccountService {

	@Override
	public boolean land(String accountName, String passWord) {
		return passWord.equals(getPassword(accountName));
	}

	public String getPassword(String accountName) {
		SqlSession session = null;
		try {
			session = MyBatisUtil.getSqlSession(true);
			AccountMapper accountMapper = session.getMapper(AccountMapper.class);
			String password = accountMapper.getPassword(accountName);
			return password;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			MyBatisUtil.closeSqlSession(session);
		}
		return "";
	}

	@Override
	public int register(Account account) {
		SqlSession session = null;
		try {
			session = MyBatisUtil.getSqlSession(true);
			AccountMapper accountMapper = session.getMapper(AccountMapper.class);
			int i = accountMapper.insertAccount(account);
			int j = 0;
			//账户插入成功
			if(i != 0) {
				//自动插入默认用户信息
				UserInfoMapper userInfoMapper = session.getMapper(UserInfoMapper.class);
				UserInfo userInfo = new UserInfo();
				userInfo.setAccount_id(account.getAccount_id());
				userInfo.setUser_name("游客"+Common.randomString());
				userInfo.setSex("男");
				userInfo.setMotto(account.getAccount_name()+"很懒,没有留下个性签名");
				j = userInfoMapper.insertUserInfo(userInfo);
			}
			System.out.println("受影响行数:"+(i+j));
			return i+j;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			MyBatisUtil.closeSqlSession(session);
		}
		return 0;
	}

	@Override
	public Integer getAccountIdByAccountName(String account_name) {
		// TODO 自动生成的方法存根
		SqlSession session = null;
		try {
			session = MyBatisUtil.getSqlSession(true);
			AccountMapper accountMapper = session.getMapper(AccountMapper.class);
			Integer i = accountMapper.getAccountIdByAccountName(account_name);
			return i;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			MyBatisUtil.closeSqlSession(session);
		}
		return null;
	}

}
